package com.cws.project.cws.clazz.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.cws.common.utils.DateUtils;
import com.cws.common.utils.security.AuthorizationUtils;
import com.cws.project.cws.clazz.domain.ClazzUser;
import com.cws.project.cws.clazz.mapper.ClazzUserMapper;
import com.cws.project.system.user.domain.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cws.project.cws.clazz.mapper.ClazzMapper;
import com.cws.project.cws.clazz.domain.Clazz;
import com.cws.project.cws.clazz.service.IClazzService;
import com.cws.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 班级信息Service业务层处理
 *
 * @author xyl
 * @date 2021-12-20
 */
@Service
public class ClazzServiceImpl implements IClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private ClazzUserMapper clazzUserMapper;

    /**
     * 查询班级信息
     *
     * @param clazzId 班级信息ID
     * @return 班级信息
     */
    @Override
    public Clazz selectClazzById(Long clazzId) {
        return clazzMapper.selectClazzById(clazzId);
    }

    /**
     * 查询班级信息列表
     *
     * @param clazz 班级信息
     * @return 班级信息
     */
    @Override
    public List<Clazz> selectClazzList(Clazz clazz) {
        return clazzMapper.selectClazzList(clazz);
    }

    /**
     * 新增班级信息
     *
     * @param clazz 班级信息
     * @return 结果
     */
    @Override
    public int insertClazz(Clazz clazz) {
        clazz.setCreateTime(DateUtils.getNowDate());
        int rows = clazzMapper.insertClazz(clazz);
        //添加用户与班级关联关联
        insertClazzUser(clazz);
        return rows;
    }

    /**
     * 修改班级信息
     *
     * @param clazz 班级信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateClazz(Clazz clazz) {
        clazz.setUpdateTime(DateUtils.getNowDate());
        // 删除用户与班级关联
        clazzUserMapper.deleteClazzUserByUserId(clazz.getUserId(),clazz.getClazzId());
        // 添加用户与班级关联关联
        insertClazzUser(clazz);
        return clazzMapper.updateClazz(clazz);
    }


    /**
     * 删除班级信息对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteClazzByIds(String ids) {
        return clazzMapper.deleteClazzByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除班级信息信息
     *
     * @param clazzId 班级信息ID
     * @return 结果
     */
    @Override
    public int deleteClazzById(Long clazzId) {
        return clazzMapper.deleteClazzById(clazzId);
    }

    @Override
    public List<Clazz> selectClazzListByUserId(Long userId) {
        return clazzMapper.selectClazzListByUserId(userId);
    }

    private void insertClazzUser(Clazz clazz) {
        ClazzUser cu = new ClazzUser();
        cu.setUserId(clazz.getUserId());
        cu.setClazzId(clazz.getClazzId());
        clazzUserMapper.insertClazzUser(cu);
    }
}
